/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MailViewComponent.java
 *
 * Created on Nov 19, 2011, 11:04:02 AM
 */
package mail.ui;

import java.io.File;
import java.util.Date;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import mail.account.UserAccount;
import mail.attribute.MailItem;
import mail.attribute.NullMailItem;
import mail.attribute.attach.Attachment;
import mail.general.FileUtils;

/**
 *
 * @author timoteo
 */
public class MailViewComponent extends javax.swing.JPanel {

    /**
     * Variable Mail Itema
     */
    private MailItem mailItem;
    /**
     * Constante que indica el modo de apertura del mail
     * Modo Lectura
     */
    public static final byte Modo_READ = 0;
    /**
     * Constante que indica el modo de apertura del mail
     * Modo Edicion
     */
    public static final byte Modo_WRITE = 1;
    /**
     * Variable para guardar el tipo de apertura del mail
     * Modo Lectura(READ)/Escritura(WRITE)
     */
    private byte modo;

    /** 
     * Creates new form MailViewComponent 
     */
    public MailViewComponent() {
        modo = Modo_READ;
        initComponents();
    }

    public void setMailItem(MailItem mailItem) {
        if (mailItem == null) {
            mailItem = new MailItem("", "", "", "");
        }
        this.mailItem = mailItem;
        loadData();
        this.updateUI();
    }

    public void setMailItem(MailItem mailItem, byte modo_Open) {
        setMailItem(mailItem);
        modo = modo_Open;
        loadData();
        this.updateUI();
    }

    public void setModo(byte modo) {
        this.modo = modo;
    }

    private void setEditable(boolean editable) {
        senderText.setEditable(editable);
        receiverText.setEditable(editable);
        subjectText.setEditable(editable);
        contentPanel.setEditable(editable);
        buttonAddAttachment.setEnabled(editable);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        senderLabel = new javax.swing.JLabel();
        receiverLabe = new javax.swing.JLabel();
        senderText = new javax.swing.JTextField();
        receiverText = new javax.swing.JTextField();
        sentDateLabel = new javax.swing.JLabel();
        sentDateText = new javax.swing.JTextField();
        subjectLabel = new javax.swing.JLabel();
        subjectText = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        contentPanel = new javax.swing.JTextPane();
        jMensajeFecha = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        JcomboFiles = new javax.swing.JComboBox();
        buttonView = new javax.swing.JButton();
        buttonAddAttachment = new javax.swing.JButton();

        senderLabel.setText("Sender:");

        receiverLabe.setText("Receiver:");

        senderText.setEditable(false);

        sentDateLabel.setText("Sent date:");

        sentDateText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sentDateTextActionPerformed(evt);
            }
        });

        subjectLabel.setText("Subject:");

        contentPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Content"));
        contentPanel.setText("text");
        jScrollPane1.setViewportView(contentPanel);

        jLabel1.setText("Files:");

        buttonView.setText("Save");
        buttonView.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonViewActionPerformed(evt);
            }
        });

        buttonAddAttachment.setText("Add");
        buttonAddAttachment.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAddAttachmentActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(senderLabel)
                            .addComponent(receiverLabe)
                            .addComponent(subjectLabel)
                            .addComponent(sentDateLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(subjectText, javax.swing.GroupLayout.DEFAULT_SIZE, 605, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jMensajeFecha))
                            .addComponent(senderText, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE)
                            .addComponent(receiverText, javax.swing.GroupLayout.DEFAULT_SIZE, 609, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(sentDateText, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(JcomboFiles, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 98, Short.MAX_VALUE)
                                .addComponent(buttonAddAttachment, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buttonView, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 664, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(senderLabel)
                    .addComponent(senderText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(receiverText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(receiverLabe))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(subjectText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(subjectLabel))
                        .addGap(11, 11, 11)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(sentDateText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(sentDateLabel)
                            .addComponent(jLabel1)
                            .addComponent(JcomboFiles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(buttonView)
                            .addComponent(buttonAddAttachment)))
                    .addComponent(jMensajeFecha))
                .addGap(30, 30, 30)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 182, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

private void sentDateTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sentDateTextActionPerformed
// TODO add your handling code here:

    Date d = new Date();
    try {
        jMensajeFecha.setText("");
        d = new Date(sentDateText.getText());
    } catch (Exception x) {
        jMensajeFecha.setText("Fecha no valida.");
        sentDateText.setText(d.getDate() + "/" + d.getMonth() + "/" + (d.getYear() + 1900));
    }
}//GEN-LAST:event_sentDateTextActionPerformed

private void buttonViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonViewActionPerformed
    viewAttachment();
}//GEN-LAST:event_buttonViewActionPerformed

private void buttonAddAttachmentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddAttachmentActionPerformed
    addAttachment();
}//GEN-LAST:event_buttonAddAttachmentActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox JcomboFiles;
    private javax.swing.JButton buttonAddAttachment;
    private javax.swing.JButton buttonView;
    private javax.swing.JTextPane contentPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jMensajeFecha;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel receiverLabe;
    private javax.swing.JTextField receiverText;
    private javax.swing.JLabel senderLabel;
    private javax.swing.JTextField senderText;
    private javax.swing.JLabel sentDateLabel;
    private javax.swing.JTextField sentDateText;
    private javax.swing.JLabel subjectLabel;
    private javax.swing.JTextField subjectText;
    // End of variables declaration//GEN-END:variables

    private void loadData() {

        if (mailItem instanceof NullMailItem) {
            LoadMailNull();
        } else {
            LoadMail();
        }

        if (modo == Modo_READ) {
            setEditable(false);
        }
        if (modo == Modo_WRITE) {
            setEditable(true);
        }
    }

    private void LoadMailNull() {
        senderText.setText("Ningun correo Seleccionado");
        contentPanel.setText("");
        Date d = new Date();
        sentDateText.setText(d.getDate() + "/" + d.getMonth() + "/" + (d.getYear() + 1900));

    }

    private void LoadMail() {
        senderText.setText(mailItem.getFromTo().getFrom().toString());
        receiverText.setText(mailItem.getFromTo().getTo().toString());
        Date d = mailItem.getDate();
        sentDateText.setText(d.getDate() + "/" + d.getMonth() + "/" + (d.getYear() + 1900));
        subjectText.setText(mailItem.getSubject());
        contentPanel.setText(mailItem.getMessage().getMessage().toString());
        loadAttachments();
    }

    private void loadAttachments() {
        JcomboFiles.removeAllItems();
        for (Attachment attachment : mailItem.getMessage().getAttachs().getAttachmentsList()) {
            JcomboFiles.addItem(attachment);
        }
        JcomboFiles.setVisible(true);
    }

    public void updateData() {
        mailItem.setFrom(new UserAccount(senderText.getText().trim()));
        mailItem.setTo(new UserAccount(receiverText.getText().trim()));
        mailItem.setSubject(subjectText.getText().trim());
        mailItem.getMessage().setContent(contentPanel.getText().trim());
    }

    private void addAttachment() {
        JFileChooser fileChooser = new JFileChooser();
        int type = fileChooser.showOpenDialog(this);
        if (type == JFileChooser.APPROVE_OPTION) {
            mailItem.getMessage().attachFile(fileChooser.getSelectedFile().getAbsolutePath());
            loadAttachments();
        }
    }

    private void viewAttachment() {
        if (JcomboFiles.getSelectedItem() != null) {
            Attachment attachment = (Attachment) JcomboFiles.getSelectedItem();
            JFileChooser chooser = new JFileChooser();
            int status = chooser.showSaveDialog(this);
            if(status == JFileChooser.APPROVE_OPTION){
                File selectedFile = chooser.getSelectedFile();
                FileUtils.writeToFile(selectedFile,attachment.getData());
            }
        }
    }
}
